package com.bauer.base.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CarInterceptor implements MethodInterceptor {

    private Enhancer enhancer = new Enhancer();

    public <T> T getProxy(Class<T> clazz) {
        //设置需要创建子类的类
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        //通过字节码技术动态创建子类实例
        return (T) enhancer.create();
    }


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("前置代理");
        Object result = methodProxy.invokeSuper(o, objects);

        //使用invoke时需要指定具体的被代理类  及替换o  为被代理对象
//        Object result = methodProxy.invoke(o, objects);
        System.out.println("后置代理");
        return result;
    }
}
